package org.richin.file.util;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FileIterable implements Iterable<File> {

	protected FileFilter filefilter=null;

	protected List<File> filelist = new ArrayList<File>();

	public FileIterable(String dirname) {
		addFiles(new File(dirname));
	}

	public FileIterable(String dirname, FileFilter filefilter) {
		this.filefilter = filefilter;
		addFiles(new File(dirname));
	}

	private void addFiles(File startDir) {
		if (startDir.isDirectory()) {
			File[] children = startDir.listFiles();
			for (int i = 0; i < children.length; i++) {
				filterAndAdd(children[i]);
				addFiles(children[i]);
			}
		} /*else {
			filterAndAdd(startDir);
		}*/
	}

	private void filterAndAdd(File file) {
		//System.out.println(file.getPath());
		if (filefilter == null) {
			filelist.add(file);
			return;
		}

		if (filefilter.accept(file)) {
			filelist.add(file);
		}
	}

	public Iterator<File> iterator() {
		return filelist.iterator();
	}

	public int size() {
		return filelist.size();
	}

	public File getFileByName(String filename) throws FileNotFoundException {
		for (File file : this) {
			if (file.getName().endsWith(filename)) {
				return file;
			}
		}

		throw new FileNotFoundException(filename);
	}
}
